package databases;

import interfaces.ExportToFile;
import interfaces.ImportFromFile;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

abstract class AbstractList<E> extends ArrayList<E> implements ExportToFile, ImportFromFile, Serializable {

/**
     * AbstractList exportToFile(File file)
     * 
     * "Sinartisi i opoia grafei se ena arxeio tipou File.Se periptwsi pou prokypsei sfalma epistrefei false.Se antitheti periptwsi epistrefei epistrefei true"
	* @param file
	* @return boolean Epistrefei false an prokypsei sfalma alliws epistrefei true
	
     */


    public boolean exportToFile(File file) {
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
            for (int i = 0; i < size(); i++)
                objectOutputStream.writeObject(get(i));
            objectOutputStream.close();
            return true;
        }
        catch (IOException exception) {
            System.out.println("Error while creating file.");
            return false;
        }
    }


/**
     * AbstractList importFromFile(File file)
     * 
     * "Sinartisi i opoia diavazei apo ena arxeio tipou File.Se periptwsi pou prokypsei sfalma epistrefei false.Se antitheti periptwsi epistrefei epistrefei true"
	* @param file
	* @return boolean Epistrefei false an prokypsei sfalma alliws epistrefei true
	
     */

    public boolean importFromFile(File file) {
        ObjectInputStream objetInputStream = null;
        try {
            if (!file.exists())
                return false;
            objetInputStream = new ObjectInputStream(new FileInputStream(file));
            while (true)
                add((E) objetInputStream.readObject());
        }
        catch (EOFException endOfFileException) {
            return true;
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        catch (ClassNotFoundException ex) {
            Logger.getLogger(AbstractList.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally {
            try {
                if (objetInputStream != null)
                    objetInputStream.close();
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return true;
    }
}
